<template>
  <div class="product-edit">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑商品' : '新增商品' }}</span>
          <div class="actions">
            <el-button @click="goBack">返回</el-button>
            <el-button type="primary" @click="submit">保存</el-button>
          </div>
        </div>
      </template>
      <el-form :model="form" label-width="110px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="名称"><el-input v-model="form.name" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货号"><el-input v-model="form.serialNumber" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="原价"
              ><el-input v-model.number="form.price" type="number"
            /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="现价"
              ><el-input v-model.number="form.discountPrice" type="number"
            /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌">
              <el-select v-model="form.brandId" placeholder="请选择品牌" style="width: 100%">
                <el-option
                  v-for="brand in brands"
                  :key="brand.brand_id"
                  :label="brand.brand_name"
                  :value="brand.brand_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类">
              <el-select v-model="form.typeId" placeholder="请选择分类" style="width: 100%">
              <el-option
                v-for="type in types"
                :key="type.typeId"
                :label="type.typeName"
                :value="type.typeId"
              />
            </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态">
          <el-switch
            :model-value="form.status === '1'"
            @change="(val) => (form.status = !!val ? '1' : '0')"
          />
        </el-form-item>
        <el-form-item label="简要描述">
          <el-input v-model="(form as any).description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="详情(HTML)" class="editor-item">
          <div class="editor-wrap">
            <QuillEditor
              v-model:content="(form as any).detailedInfo"
              contentType="html"
              theme="snow"
              class="editor"
            />
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 库存管理模块 -->
    <el-card v-if="isEdit && form.shoeId" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>库存管理</span>
          <el-button type="primary" size="small" @click="openStockAdd">新增库存</el-button>
        </div>
      </template>
      <el-table
        :data="stocks"
        v-loading="stockLoading"
        @selection-change="handleStockSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="尺码" min-width="100">
          <template #default="{ row }">
            {{ row.size?.shoeSize || '未知尺码' }}
          </template>
        </el-table-column>
        <el-table-column label="颜色" min-width="100">
          <template #default="{ row }">
            {{ row.color?.colorName || '未知颜色' }}
          </template>
        </el-table-column>
        <el-table-column label="价格" prop="price" min-width="100" />
        <el-table-column label="折扣价" prop="discountPrice" min-width="100" />
        <el-table-column label="库存数量" prop="stockQuantity" min-width="120" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="openStockEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleStockDelete(row.shoeId, row.sizeId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="stock-toolbar" style="margin-top: 12px">
        <el-button
          type="danger"
          size="small"
          :disabled="!selectedStocks.length"
          @click="batchStockDelete"
          >批量删除</el-button
        >
      </div>
    </el-card>

    <!-- 库存编辑对话框 -->
    <el-dialog
      :title="stockEditing ? '编辑库存' : '新增库存'"
      :model-value="stockDialogVisible"
      :width="isMobile ? '95vw' : '520px'"
      @close="closeStockDialog"
      :class="{ 'mobile-dialog': isMobile }"
    >
      <el-form :model="stockForm" label-width="90px" :class="{ 'mobile': isMobile }">
        <el-form-item label="尺码">
          <el-select 
            v-model="stockForm.sizeId" 
            placeholder="请选择尺码" 
            style="width: 100%"
            :size="isMobile ? 'large' : 'default'"
          >
            <el-option
              v-for="size in sizes"
              :key="size.sizeId"
              :label="size.shoeSize"
              :value="size.sizeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="颜色">
          <el-select 
            v-model="stockForm.colorId" 
            placeholder="请选择颜色" 
            style="width: 100%"
            :size="isMobile ? 'large' : 'default'"
          >
            <el-option
              v-for="color in colors"
              :key="color.colorId"
              :label="color.colorName"
              :value="color.colorId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格">
          <el-input 
            v-model.number="stockForm.price" 
            type="number" 
            :size="isMobile ? 'large' : 'default'"
          />
        </el-form-item>
        <el-form-item label="折扣价">
          <el-input 
            v-model.number="stockForm.discountPrice" 
            type="number" 
            :size="isMobile ? 'large' : 'default'"
          />
        </el-form-item>
        <el-form-item label="库存数量">
          <el-input 
            v-model.number="stockForm.stockQuantity" 
            type="number" 
            :size="isMobile ? 'large' : 'default'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" :class="{ 'mobile': isMobile }">
          <el-button 
            @click="closeStockDialog"
            :size="isMobile ? 'large' : 'default'"
            class="cancel-btn"
          >
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="submitStock"
            :size="isMobile ? 'large' : 'default'"
            class="save-btn"
          >
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { productService } from '@/api'
import { ElMessage, ElMessageBox } from 'element-plus'

type ShoesForm = {
  shoeId?: number
  name?: string
  serialNumber?: string
  price?: number
  discountPrice?: number
  brandId?: number
  typeId?: number
  status?: string
  description?: string
  detailedInfo?: string
}

type Brand = {
  brand_id: number
  brand_name: string
  status: number
  remarks?: string
}

type Type = {
  typeId: number
  typeName: string
  status: number
  remarks?: string
}

type Size = {
  sizeId: number
  shoeSize: string
  status: number
}

type Color = {
  colorId: number
  colorName: string
  status: number
}

type StockRow = {
  skuId?: number
  shoeId: number
  sizeId: number
  colorId: number
  price: number
  discountPrice?: number
  stockQuantity: number
  size?: { shoeSize: string }
  color?: { colorName: string }
}

const route = useRoute()
const router = useRouter()
const form = ref<ShoesForm>({ status: '1' })
const isEdit = computed(() => !!route.params.id)

// 下拉选择数据
const brands = ref<Brand[]>([])
const types = ref<Type[]>([])
const sizes = ref<Size[]>([])
const colors = ref<Color[]>([])

// 库存管理相关
const stocks = ref<StockRow[]>([])
const stockLoading = ref(false)
const selectedStocks = ref<StockRow[]>([])
const stockDialogVisible = ref(false)
const stockEditing = ref(false)
const stockForm = ref<Partial<StockRow>>({ shoeId: 0, sizeId: 0, colorId: 0, stockQuantity: 0 })
let editingStockKey: { shoeId: number; sizeId: number } | null = null

// 移动端判断
const isMobile = computed(() => window.innerWidth < 768)

// 加载基础数据
const loadBrands = async () => {
  try {
    const res = await productService.getBrandsList()
    if ((res.data as any).code === 200) {
      brands.value = (res.data as any).data || []
    }
  } catch (error) {
    console.error('加载品牌列表失败:', error)
  }
}

const loadTypes = async () => {
  try {
    const res = await productService.getTypesList()
    if ((res.data as any).code === 200) {
      types.value = (res.data as any).data || []
    }
  } catch (error) {
    console.error('加载分类列表失败:', error)
  }
}

const loadSizes = async () => {
  try {
    const res = await productService.getSizesList()
    if ((res.data as any).code === 200) {
      sizes.value = (res.data as any).data || []
    }
  } catch (error) {
    console.error('加载尺码列表失败:', error)
  }
}

const loadColors = async () => {
  try {
    const res = await productService.getColorsList()
    if ((res.data as any).code === 200) {
      colors.value = (res.data as any).data || []
    }
  } catch (error) {
    console.error('加载颜色列表失败:', error)
  }
}

const loadDetail = async () => {
  if (!isEdit.value) return
  const id = Number(route.params.id)
  if (!id) return
  const res = await productService.getShoesDetail(id)
  const data: any = res.data?.data
  if (data) {
    form.value = {
      shoeId: data.shoeId,
      name: data.name,
      serialNumber: data.serialNumber,
      price: data.price,
      discountPrice: data.discountPrice,
      brandId: data.brandId,
      typeId: data.typeId,
      status: data.status ?? '1',
      description: data.description,
      detailedInfo: data.detailedInfo,
    }
  }
}

// 库存管理方法
const loadStocks = async () => {
  if (!form.value.shoeId) return
  stockLoading.value = true
  try {
    const res = await productService.getStockListByProduct(form.value.shoeId)
    if ((res.data as any).code === 200) {
      stocks.value = (res.data as any).data || []
    }
  } catch (error) {
    console.error('加载库存列表失败:', error)
  } finally {
    stockLoading.value = false
  }
}

const openStockAdd = () => {
  stockEditing.value = false
  editingStockKey = null
  stockForm.value = {
    shoeId: form.value.shoeId,
    sizeId: 0,
    colorId: 0,
    price: form.value.price || 0,
    discountPrice: form.value.discountPrice || 0,
    stockQuantity: 0,
  }
  stockDialogVisible.value = true
}

const openStockEdit = (stock: StockRow) => {
  stockEditing.value = true
  editingStockKey = { shoeId: stock.shoeId, sizeId: stock.sizeId }
  stockForm.value = {
    skuId: stock.skuId, // 确保包含skuId
    shoeId: stock.shoeId,
    sizeId: stock.sizeId,
    colorId: stock.colorId,
    price: stock.price,
    discountPrice: stock.discountPrice,
    stockQuantity: stock.stockQuantity,
  }
  stockDialogVisible.value = true
}

const closeStockDialog = () => {
  stockDialogVisible.value = false
}

const submitStock = async () => {
  try {
    if (stockEditing.value && editingStockKey) {
      // 确保更新时包含skuId
      if (!stockForm.value.skuId) {
        ElMessage.error('缺少库存ID，无法更新')
        return
      }
      await productService.updateStock(stockForm.value as any)
      ElMessage.success('库存更新成功')
    } else {
      await productService.addStock(stockForm.value as any)
      ElMessage.success('库存添加成功')
    }
    stockDialogVisible.value = false
    await loadStocks()
  } catch (error) {
    ElMessage.error('操作失败')
    console.error('库存操作失败:', error)
  }
}

const handleStockDelete = async (shoeId: number, sizeId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这条库存记录吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await productService.deleteStock(shoeId, sizeId)
    ElMessage.success('删除成功')
    await loadStocks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除库存失败:', error)
    }
  }
}

const handleStockSelectionChange = (rows: StockRow[]) => {
  selectedStocks.value = rows
}

const batchStockDelete = async () => {
  if (!selectedStocks.value.length) return
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedStocks.value.length} 条库存记录吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
    await Promise.all(
      selectedStocks.value.map((item) => productService.deleteStock(item.shoeId, item.sizeId)),
    )
    selectedStocks.value = []
    ElMessage.success('批量删除成功')
    await loadStocks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
      console.error('批量删除库存失败:', error)
    }
  }
}

const goBack = () => router.push('/admin/products')

const submit = async () => {
  try {
    if (isEdit.value) {
      await productService.updateShoes(form.value as Record<string, unknown>)
      ElMessage.success('商品更新成功')
    } else {
      const res = await productService.addShoes(form.value as Record<string, unknown>)
      ElMessage.success('商品添加成功')
      // 如果是新增商品，获取返回的商品ID用于库存管理
      if ((res.data as any)?.data?.shoeId) {
        form.value.shoeId = (res.data as any).data.shoeId
      }
    }
  } catch (error) {
    ElMessage.error('操作失败')
    console.error('商品操作失败:', error)
    return
  }
  goBack()
}

// 监听商品ID变化，加载库存数据
watch(
  () => form.value.shoeId,
  (newShoeId) => {
    if (newShoeId && isEdit.value) {
      loadStocks()
    }
  },
)

onMounted(async () => {
  await Promise.all([loadBrands(), loadTypes(), loadSizes(), loadColors(), loadDetail()])
})
</script>

<style scoped>
.product-edit {
  padding: 20px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.actions {
  display: flex;
  gap: 8px;
}

.editor-wrap {
  width: 100%;
}

.editor {
  width: 100%;
}

/* 移动端适配样式 */
@media (max-width: 768px) {
  .product-edit {
    padding: 12px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .el-form {
    &.mobile {
      .el-form-item {
        margin-bottom: 20px;
        
        .el-form-item__label {
          font-size: 14px;
          font-weight: 500;
          margin-bottom: 8px;
        }
        
        .el-input,
        .el-select,
        .el-textarea {
          .el-input__inner,
          .el-textarea__inner {
            height: 44px;
            font-size: 16px;
            border-radius: 8px;
          }
        }
        
        .el-switch {
          .el-switch__core {
            width: 50px;
            height: 28px;
          }
        }
      }
    }
  }
  
  .el-table {
    .el-table__header,
    .el-table__body {
      font-size: 14px;
    }
    
    .el-button {
      height: 36px;
      font-size: 14px;
      border-radius: 6px;
    }
  }
  
  .stock-toolbar {
    .el-button {
      width: 100%;
      height: 44px;
      font-size: 16px;
      border-radius: 8px;
    }
  }
}

/* 移动端对话框样式 */
:deep(.mobile-dialog) {
  .el-dialog {
    margin: 10px auto !important;
    border-radius: 16px;
    
    .el-dialog__header {
      padding: 20px 20px 16px;
      
      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
      }
    }
    
    .el-dialog__body {
      padding: 0 20px 20px;
    }
    
    .el-dialog__footer {
      padding: 0 20px 20px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  
  &.mobile {
    flex-direction: column;
    gap: 10px;
    
    .el-button {
      width: 100%;
      height: 48px;
      font-size: 16px;
      border-radius: 8px;
      font-weight: 500;
    }
  }
  
  .cancel-btn {
    background-color: #f5f7fa;
    border-color: #dcdfe6;
    color: #606266;
    font-weight: 500;
    
    &:hover {
      background-color: #ebeef5;
      border-color: #dcdfe6;
      color: #409eff;
    }
  }
  
  .save-btn {
    background-color: #409eff;
    border-color: #409eff;
    color: #fff;
    font-weight: 500;
    
    &:hover {
      background-color: #66b1ff;
      border-color: #66b1ff;
      color: #fff;
    }
  }
}

/* 平板端优化 */
@media (min-width: 769px) and (max-width: 1024px) {
  .product-edit {
    padding: 16px;
  }
  
  .el-form {
    .el-form-item {
      margin-bottom: 18px;
      
      .el-form-item__label {
        font-size: 14px;
      }
    }
  }
  
  .el-table {
    .el-button {
      height: 32px;
      font-size: 13px;
    }
  }
}
</style>
